package com.sl.plugin.step.selenium.scroll;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.sl.core.engine.meta.impl.AbstractProcessCompDescriptor;
import com.sl.core.engine.step.ProcessCompService;
import com.sl.core.engine.step.impl.AbstractProcessComp;
import lombok.SneakyThrows;
import org.apache.commons.compress.utils.Lists;
import org.openqa.selenium.*;

import java.util.List;

/**
 */
public class SeleniumScrollComp extends AbstractProcessComp<WebDriver, WebDriver> implements ProcessCompService {


    public SeleniumScrollComp(AbstractProcessCompDescriptor abstractProcessCompDescriptor) {
        super(abstractProcessCompDescriptor);
    }


    @SneakyThrows
    @Override
    public WebDriver input(WebDriver driver) {
        JavascriptExecutor js = (JavascriptExecutor) driver;

        String cssSelector = meta.getStrAttr("cssSelector");
        Integer scrollTop = meta.getIntAttr("scrollTop");
        Integer scrollLeft = meta.getIntAttr("scrollLeft");

        if (StrUtil.isNotBlank(cssSelector)) {
            //左右上下滑动指定元素的滚动条
            if (ObjectUtil.isNotNull(scrollTop)) {
                js.executeScript("document.querySelector('arguments[0]').scrollTop=arguments[1];", cssSelector, scrollTop);
            }
            if (ObjectUtil.isNotNull(scrollLeft)) {
                js.executeScript("document.querySelector('arguments[0]').scrollLeft=arguments[1];", cssSelector, scrollLeft);
            }
        } else {
            //左右上下滑动window窗体的滚动条
            js.executeScript("window.scrollTo(arguments[0],arguments[1]);", scrollTop, scrollLeft);
        }

        //有些网站的元素他的事件相关js,是根据可视化窗口来,当元素在可视化窗口内,就会调用对应的js绑定事件,那么我们可以这样
        //找到元素,以渲染完毕
        // WebElement elementa = driver.findElement(By.cssSelector(cssSelector));
        // 移动滚动条将,对应的元素显示,在可视化窗口中
        //  js.executeScript("window.scrollTo(0,arguments[0].getBoundingClientRect().top-100)",elementa);
        //展开下拉列表
        // elementa.click();
        // 有些列表内的元素是懒加载,如果我们直接将滚动条滑动到底部,元素是不会加载出来的,触发懒加载需要时间的,那么我们需要模拟人为滑动滚动条的方式来触发列表中所有元素让他们进行加载
        //获取需要滚动的距离
//        Long o = (Long) js.executeScript("let elementsByClassNameElement = document.querySelector(arguments[0]);\n" + " return elementsByClassNameElement.offsetHeight+elementsByClassNameElement.offsetTop;", cssSelector);
//        //获取当前滚动条位置
//        Long o1 = (Long) js.executeScript("return document.documentElement.scrollTop;");
//        // 向下移动滚动条让列表的内容懒加载出来
//        for (Long i = o1; i < o; i += 500) {
//            js.executeScript("window.scrollTo(0,arguments[0]);", i);
//            Thread.sleep(50);
//        }
        return driver;
    }

}
